import {
  queryProductLineList,
  queryOriginalFactoryList,
  queryDistributorList,
  addNewspaperDate,
  editNewspaperDate,
  newspaperDateConfigList
} from '@api/system_config_v1.js';
import {formatDate} from '@const/filter'
export default {
  data() {
    return {
      params: {
        productLineCode: '',
        newspaperStartDate: formatDate(new Date(), 'YYYY-MM'),
        newspaperEndDate: formatDate(new Date(), 'YYYY-MM'),
      },
      transferTitles: ['经销商', '适用经销商'],
      originalFactoryList: [],
      productLineList: [],
      originalFactoryMap: {},
      productLineMap: {},
      distributorListMap: {},
      checkList: [],
      selectList: [],
      orderTypeList: [],
      loading: false,
      switchValue: false,
      attributeType: 1,
      orderTypeInfo: [],
      optionList: [],
      transferData: [],
      transferValue: []
    }
  },
  created() {
    this.pickerOptions = {
      disabledDate: time => {
        const now = new Date()
        return now.getFullYear() > time.getFullYear() || now.getFullYear() === time.getFullYear() && now.getMonth() > time.getMonth()
      }
    }
    this.initData()
    this.initGlobalBtn()
    this.queryProductLineCode = this.$route.query.queryProductLineCode
    this.queryProductLineCode && this.getInfo()
  },
  methods: {
    initData () {
      this.newspaperEndDayList = new Array(31).fill('').map((x, i) => {return {label: `${i + 1}日`, value: i + 1}})
    },
    async getInfo () {
      this.initGlobalBtn()
      let data = {}
      await this.$axios.$post(newspaperDateConfigList, {
        productLineCode: this.queryProductLineCode,
        newspaperDateConfigType: 2
      }).then(({payload}) => {
        data = payload.content[0]
      })
      let obj = {
        productLineCode: data.productLineCode,
        originalFactoryCode: data.originalFactoryCode,
        configSaleDateId: data.configSaleDateId,
        newspaperEndDay: Number(data.newspaperEndDay),
        newspaperMonth: data.newspaperEndDate.indexOf('本月度') > -1 ? 1 : 2
      }
      this.queryOriginalFactoryList(data.originalFactoryName)
      await this.queryProductLineList()
      if (data.startValidate && data.endValidate) {
        obj.newspaperStartDate = formatDate(new Date(data.startValidate), 'YYYY-MM')
        obj.newspaperEndDate = formatDate(new Date(data.endValidate), 'YYYY-MM')
      }
      this.params = obj
      this.productLineChange(data.productLineCode)
      this.transferValue = data.applyCompanyAccountNumberList || []
    },
    initGlobalBtn() {
      let btnObj = {
        type: 'btn',
        arr: [{ type: '', val: '返回', handle: this.goBack }]
      };
      let submitBtn = {
        type: 'primary',
        val: this.queryProductLineCode ? '修改' : '提交',
        handle: this.onSubmit
      };
      btnObj.arr.push(submitBtn);
      this.$store.commit('changeLayoutHandle', btnObj);
    },
    goBack () {
      this.$router.push({
        path: '/system-config/announcement-date-configuration',
        query: {
          type: 'temporary'
        }
      })
    },
    onSubmit () {
      let next = true
      let msg = ''
      const rules = [
        {key: 'originalFactoryCode', msg: '请选择原厂'},
        {key: 'productLineCode', msg: '请选择产品线'},
        {key: 'newspaperMonth', msg: '请选择报台截止日期'},
        {key: 'newspaperEndDay', msg: '请选择报台截止日期'}
      ]
      rules.forEach(rule => {
        if (!this.params[rule.key]) {
          if (next) {
            next = false
            msg = rule.msg
          }
        }
      })
      if (new Date(this.params.newspaperStartDate) > new Date(this.params.newspaperEndDate)) {
        if (next) {
          next = false
          msg = '有效期开始日期不能晚于结束日期'
        }
      }
      if (!this.transferValue.length) {
        if (next) {
          next = false
          msg = '请选择适用经销商'
        }
      }
      if (!next) return this.$message.warning(msg)
      let sendData = {
        newspaperDateType: 2,
        newspaperEndDay: this.params.newspaperEndDay,
        newspaperStartDate: this.params.newspaperStartDate,
        newspaperEndDate: this.params.newspaperEndDate,
        originalFactoryCode: this.params.originalFactoryCode,
        originalFactoryName: this.originalFactoryMap[this.params.originalFactoryCode],
        newspaperMonth: this.params.newspaperMonth,
        productLineInfoList: [
          {
            productLineCode: this.params.productLineCode,
            productLineName: this.productLineMap[this.params.productLineCode]
          }
        ],
        companyInfoList: []
      }
      this.transferValue.forEach(item => {
        sendData.companyInfoList.push({
          companyAccountNum: item,
          companyName: this.distributorListMap[item]
        })
      })
      let ex = addNewspaperDate
      let sendMsg = '添加成功'
      if (this.queryProductLineCode) {
        ex = editNewspaperDate
        sendData.configSaleDateId = this.params.configSaleDateId
        sendMsg = '修改成功'
      }
      this.$axios.$post(ex, sendData).then(res => {
        this.$message.success(sendMsg)
        this.goBack()
      });
    },
    // 原厂下拉
    queryOriginalFactoryList(val) {
      if (val !== '') {
        this.loading = true;
        let query = {
          originalFactoryName: val,
        };
        this.$axios.$post(queryOriginalFactoryList, query).then(res => {
          this.setOriginList(res.payload, 'originalFactoryList', 'originalFactoryMap')
          this.loading = false;
        });
      }
    },
    // 产品线下拉
    queryProductLineList (val) {
      this.loading = true;
      this.params.productLineCode = ''
      let query = {
        originalFactoryCode: this.params.originalFactoryCode,
        productLineName: val
      };
      return this.$axios.$post(queryProductLineList, query).then(res => {
        this.productLineList = res.payload
        this.productLineMap = {}
        res.payload.forEach(item => {
          this.productLineMap[item.productLineCode] = item.productLineName
        })
        this.transferValue = []
        this.transferData = []
        this.loading = false;
      });
    },
    productLineChange (v) {
      this.transferTitles.splice(0, 1, this.productLineMap[v] + '的经销商')
      this.getDistributorList()
    },
    getDistributorList () {
      this.transferValue = []
      this.transferData = []
      const query = {
        originalFactoryCode: this.params.originalFactoryCode,
        productLineCode: this.params.productLineCode
      }
      this.$axios.$post(queryDistributorList, query).then(res => {
        res.payload.forEach(item => {
          this.distributorListMap[item.companyAccountNum] = item.companyName
          this.transferData.push({
            key: item.companyAccountNum,
            label: item.companyName
          })
        })
      });
    },
    setOriginList (data, key, mapKey) {
      this[key] = data
      data.forEach(item => {
        this[mapKey][item.originalFactoryCode] = item.originalFactoryName
      })
    }
  }
};
